package com.borderbears.backend.gui.dockables;

import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;

import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTree;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.tree.TreeModel;

import com.borderbears.backend.actions.LoadMediaAction;
import com.borderbears.backend.media.MediaManager;
import com.borderbears.backend.media.MediaNode;
import com.vlsolutions.swing.docking.DockKey;
import com.vlsolutions.swing.docking.Dockable;

public class TreePanel extends JPanel implements Dockable {

	public static final String ACTION_SELECTION_CHANGED = "selectionChanged";

	DockKey dockKey = new DockKey("Navigator");

	private final List<ActionListener> listeners = new ArrayList<ActionListener>();

	private JTree tree;
	private JLabel lbStatus;

	private MediaNode selectedNode;

	public TreePanel(final DockKey key) {
		dockKey = key;
		createUI();
	}

	private void createUI() {
		setLayout(new BorderLayout());

		tree = new JTree();
		tree.addTreeSelectionListener(treeSelectionListener);
		tree.setModel(MediaManager.getInstance().getTreeModel());
		final JScrollPane spTree = new JScrollPane(tree);
		add(spTree, BorderLayout.CENTER);

		final JButton btReload = new JButton(new LoadMediaAction());

		final JPanel pNorth = new JPanel(new FlowLayout(FlowLayout.LEFT));
		pNorth.add(btReload);

		add(pNorth, BorderLayout.NORTH);

		final JPanel pSouth = new JPanel(new FlowLayout(FlowLayout.LEFT));
		lbStatus = new JLabel();
		pSouth.add(lbStatus);
		add(pSouth, BorderLayout.SOUTH);

		//setModel(null);

	}

	public MediaNode getSelectedNode() {
		return selectedNode;
	}

	public void setModel(final TreeModel model) {
		tree.setModel(model);
		if (null == model) {
			lbStatus.setText("No data loaded.");
		}
	}

	public Component getComponent() {
		return this;
	}

	public DockKey getDockKey() {
		return dockKey;
	}

	public void addActionListener(final ActionListener l) {
		if (!listeners.contains(l)) {
			listeners.add(l);
		}
	}

	public void removeActionListener(final ActionListener l) {
		listeners.remove(l);
	}

	private final TreeSelectionListener treeSelectionListener = new TreeSelectionListener() {
		public void valueChanged(final TreeSelectionEvent e) {
			selectedNode = (MediaNode) e.getPath().getLastPathComponent();
			final ActionEvent ev = new ActionEvent(this, 0, ACTION_SELECTION_CHANGED);
			for (final ActionListener l : listeners) {
				l.actionPerformed(ev);
			}
		}

	};

}
